﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;
using System.IO;

namespace StockFinder.HistoricalPriceAnalysers
{
    public class EveryPriceMoveFinderHistoricalPriceAnalyser
    {
        public List<HistoricPriceAnalyserResult> AnalysePrices(List<DailyPrice> prices, decimal maxDrawdown)
        {
            var results = new List<HistoricPriceAnalyserResult>();
            var orderedPrices = prices.OrderBy(p => p.PriceDate).ToArray();

            var output = new StringBuilder();
            output.AppendLine("Date,High,Drawdown,Days");

            int priceCount = orderedPrices.Count();

            for (int i = 0; i < priceCount; i++)
            {
                var currentPrice = orderedPrices[i];
                decimal lastHigh = currentPrice.AdjustedClose;

                var futurePrices = orderedPrices.Skip(i + 1).ToArray();

                int futurePricesCount = futurePrices.Count();

                for (int j = 0; j < futurePricesCount; j++)
                {
                    var currentFuturePrice = futurePrices[j];

                    if (currentFuturePrice.AdjustedClose > lastHigh)
                    {
                        lastHigh = currentFuturePrice.AdjustedClose;
                    }

                    //are we at drawdown?
                    var drawdown = ((lastHigh - currentFuturePrice.AdjustedClose) / lastHigh) * 100;

                    var moveFromInitial = ((lastHigh - currentPrice.AdjustedClose) / currentPrice.AdjustedClose) * 100;

                    if (drawdown >= maxDrawdown)
                    {
                        results.Add(new HistoricPriceAnalyserResult()
                        {
                            LastPriceDate = currentPrice.PriceDate,
                            DepthFromHigh = moveFromInitial,
                            BaseDepth = drawdown,
                            BaseLength = (currentFuturePrice.PriceDate - currentPrice.PriceDate).Days
                        });

                        break;
                    }
                }
            }

            return results;
        }
    }
}
